<template>
  <div class="bridge-work-container">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="display: flex;justify-content: space-between;width: 100%;">
            <div>
              <el-form-item label="工作名称" prop="workName">
                <el-input v-model="queryParams.workName" placeholder="请输入工作名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="工作类型" prop="workType">
                <el-select v-model="queryParams.workType" placeholder="请选择工作类型" clearable style="width: 180px">
                  <el-option label="日常维护" :value="1" />
                  <el-option label="应急处理" :value="2" />
                  <el-option label="定期检查" :value="3" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              </el-form-item>
            </div>
            <div>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" icon="Plus" class="add-button" @click="handleAdd">新增</el-button>
            </div>
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange" class="custom-table">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="workType" label="工作类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getWorkTypeTagType(row.workType)">
            {{ row.workType }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="summaryTime" label="总结时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.summaryTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="responsible" label="负责人" width="120" />
      <el-table-column prop="workContent" label="工作内容" min-width="200" show-overflow-tooltip />
      <el-table-column prop="mainAchievements" label="主要成果" min-width="180" show-overflow-tooltip />
      <el-table-column prop="attachments" label="附件" width="100" align="center">
        <template #default="{ row }">
          <el-link v-if="row.ossList && row.ossList.length > 0" type="primary" :underline="false" @click="handleViewAttachment(row)">
            <el-icon>
              <Document />
            </el-icon>
            查看附件
          </el-link>
          <el-button v-else link type="primary" @click="handleUploadAttachment(row)">
            <el-icon>
              <Upload />
            </el-icon>
            上传
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)" class="operation-button"> 编辑</el-button>
          <el-button link @click="handleDelete(row)" class="operation-button danger"> 删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        background
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="60%" class="custom-dialog">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="dialog-form">
        <el-form-item label="工作类型" prop="workType">
          <el-select v-model="form.workType" placeholder="请选择工作类型" class="w-full">
            <el-option value="日常工作" label="日常工作" />
            <el-option value="应急处置" label="应急处置" />
            <el-option value="专项工作" label="专项工作" />
            <el-option value="重点项目" label="重点项目" />
            <el-option value="其他工作" label="其他工作" />
          </el-select>
        </el-form-item>
        <el-form-item label="总结时间" prop="summaryTime">
          <el-date-picker
            v-model="form.summaryTime"
            type="datetime"
            placeholder="选择总结时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="new Date(2000, 1, 1, 0, 0, 0)"
            class="w-full"
          />
        </el-form-item>
        <el-form-item label="负责人" prop="responsible">
          <el-input v-model="form.responsible" placeholder="请输入负责人姓名" />
        </el-form-item>
        <el-form-item label="工作内容" prop="workContent">
          <el-input type="textarea" v-model="form.workContent" :rows="3" placeholder="请详细描述工作内容" />
        </el-form-item>
        <el-form-item label="主要成果" prop="mainAchievements">
          <el-input type="textarea" v-model="form.mainAchievements" :rows="3" placeholder="请描述工作取得的主要成果" />
        </el-form-item>
        <el-form-item label="存在问题" prop="existingProblems">
          <el-input type="textarea" v-model="form.existingProblems" :rows="3" placeholder="请描述工作中存在的问题" />
        </el-form-item>
        <el-form-item label="改进建议" prop="improvements">
          <el-input type="textarea" v-model="form.improvements" :rows="3" placeholder="请提出改进建议" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" v-model="form.remarks" :rows="2" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      -
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 附件列表弹窗 -->
    <el-dialog v-model="attachmentDialogVisible" title="附件列表" width="600px" class="attachment-dialog">
      <div class="attachment-container">
        <el-table :data="attachmentList" style="width: 100%">
          <el-table-column prop="fileName" label="文件名称" />
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleDownload(row)">
                <el-icon>
                  <Download />
                </el-icon>
                下载
              </el-button>
              <el-button type="danger" link @click="handleDeleteAttachment(row)">
                <el-icon>
                  <Delete />
                </el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 文件上传对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传附件" width="500px" class="custom-dialog">
      <div class="upload-container">
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :limit="10"
          :on-exceed="handleExceed"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          :before-upload="beforeUpload"
          multiple
          action="#"
          :file-list="uploadFiles"
        >
          <template #trigger>
            <el-button type="primary">
              <el-icon>
                <Plus />
              </el-icon>
              选择文件
            </el-button>
          </template>
          <template #tip>
            <div class="el-upload__tip">支持任意格式文件，单个文件不超过10MB</div>
          </template>
        </el-upload>

        <div v-if="uploadProgress.total > 0" class="upload-progress">
          <div class="progress-text">
            正在上传: {{ uploadProgress.current }}/{{ uploadProgress.total }}
            <div class="progress-status">
              <span v-if="uploadProgress.status === 'success'" class="success-text">上传完成</span>
              <span v-else-if="uploadProgress.status === 'exception'" class="error-text">上传失败</span>
              <span v-else>上传中...</span>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUpload" :loading="uploading" :disabled="!uploadFiles.length"> 开始上传 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 文件预览弹窗 (旧的，可以删除) -->
    <el-dialog v-model="fileDialogVisible" title="相关附件" width="50%" class="file-dialog">
      <div class="file-list">
        <div v-for="(file, index) in currentFiles" :key="index" class="file-item">
          <el-link :href="file.url" target="_blank" type="primary">
            <el-icon>
              <Document />
            </el-icon>
            {{ file.name }}
          </el-link>
        </div>
      </div>
      <template #footer>
        <el-button @click="fileDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance, type ComponentInternalInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import { Plus, Document, Upload, Download, Delete } from '@element-plus/icons-vue';
import { getWorkSummary, addWorkSummary, updateEWorkSummary, deleteWorkSummary, getWorkSummaryInfo } from '@/api/bridge/command/work';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 定义类型
interface WorkSummary {
  id: string;
  workType: string;
  summaryTime: string;
  responsible: string;
  workContent: string;
  mainAchievements: string;
  existingProblems: string;
  improvements: string;
  remarks: string;
  ossList?: Array<{
    ossId: string;
    fileName: string;
    url: string;
  }>;
}

// 表格数据
const tableData = ref<WorkSummary[]>([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedRows = ref<WorkSummary[]>([]);
const showSearch = ref(true);

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref();
const form = ref<WorkSummary>({
  id: '',
  workType: '',
  summaryTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  responsible: '',
  workContent: '',
  mainAchievements: '',
  existingProblems: '',
  improvements: '',
  remarks: '',
  ossList: []
});

// 旧的文件相关 (可以保留以避免代码报错，但这些将被新的替代)
const fileDialogVisible = ref(false);
const currentFiles = ref([]);
const fileList = ref([]);

// 新增的附件相关
const attachmentDialogVisible = ref(false);
const attachmentList = ref([]);
const uploadDialogVisible = ref(false);
const uploadRef = ref();
const uploadFiles = ref([]);
const currentRow = ref(null);
const uploading = ref(false);
const uploadProgress = ref({
  current: 0,
  total: 0,
  status: '' as '' | 'success' | 'exception' | 'warning'
});

// 表单校验规则
const rules = {
  workType: [{ required: true, message: '请选择工作类型', trigger: 'change' }],
  summaryTime: [{ required: true, message: '请选择总结时间', trigger: 'change' }],
  responsible: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  workContent: [{ required: true, message: '请输入工作内容', trigger: 'blur' }],
  mainAchievements: [{ required: true, message: '请输入主要成果', trigger: 'blur' }]
};

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return '-';
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

const queryParams = ref({
  dictType: '',
  pageNum: 1,
  pageSize: 100,
  dictName: '',
  location: '',
  workContent: '',
  dictLabel: '',
  workName: '',
  workType: null
});

const queryFormRef = ref<any>(null);

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  fetchTableData();
};

const resetQuery = () => {
  // 在这里添加重置逻辑
  queryParams.value.workContent = null;
  queryFormRef.value?.resetFields();
  // 调用查询接口
  fetchTableData();
};

// 获取工作类型标签样式
const getWorkTypeTagType = (type) => {
  const typeMap = {
    '日常工作': 'info',
    '应急处置': 'danger',
    '专项工作': 'warning',
    '重点项目': 'success',
    '其他工作': ''
  };
  return typeMap[type] || '';
};

// 获取状态名称
const getStatusName = (status) => {
  const statusMap = {
    1: '已完成',
    2: '进行中',
    3: '待开始'
  };
  return statusMap[status] || '-';
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    1: 'success',
    2: 'warning',
    3: 'info'
  };
  return statusMap[status] || '';
};

// 获取表格数据
const fetchTableData = async () => {
  try {
    loading.value = true;
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    };
    const res = await getWorkSummary(params);
    if (res.code === 200) {
      tableData.value = res.rows || [];
      total.value = res.total;
    }
  } catch (error) {
    console.error('获取工作总结列表失败:', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 处理附件查看
const handleViewAttachment = (row) => {
  if (row.ossList && row.ossList.length > 0) {
    attachmentList.value = row.ossList;
    attachmentDialogVisible.value = true;
  } else {
    ElMessage.warning('暂无附件');
  }
};

// 处理附件上传点击
const handleUploadAttachment = (row) => {
  currentRow.value = row;
  uploadDialogVisible.value = true;
  uploadFiles.value = [];
  uploadProgress.value = {
    current: 0,
    total: 0,
    status: ''
  };
};

// 处理文件选择
const handleFileChange = (file, fileList) => {
  uploadFiles.value = fileList;
};

// 处理文件移除
const handleFileRemove = (file, fileList) => {
  uploadFiles.value = fileList;
};

// 处理超出文件数限制
const handleExceed = () => {
  ElMessage.warning('最多只能上传10个文件');
};

// 提交文件上传
const submitUpload = async () => {
  if (!uploadFiles.value.length) {
    ElMessage.warning('请先选择要上传的文件');
    return;
  }

  uploading.value = true;
  uploadProgress.value.total = uploadFiles.value.length;
  uploadProgress.value.current = 0;
  uploadProgress.value.status = '';

  try {
    // 这里应该调用上传附件的API，目前暂时模拟上传过程
    for (const file of uploadFiles.value) {
      // 模拟上传过程
      await new Promise((resolve) => setTimeout(resolve, 500));
      uploadProgress.value.current++;
    }

    uploadProgress.value.status = 'success';
    ElMessage.success('文件上传成功');
    await fetchTableData(); // 刷新列表
    setTimeout(() => {
      uploadDialogVisible.value = false;
      uploading.value = false;
      uploadFiles.value = [];
    }, 1000);
  } catch (error) {
    uploadProgress.value.status = 'exception';
    ElMessage.error('文件上传失败');
    uploading.value = false;
  }
};

// 上传前校验
const beforeUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!');
    return false;
  }
  return true;
};

// 删除附件
const handleDeleteAttachment = (file) => {
  ElMessageBox.confirm(`确定要删除文件 "${file.fileName}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        // 这里应该调用删除附件的API，目前仅模拟过程
        ElMessage.success('删除成功');
        // 从当前列表中移除
        attachmentList.value = attachmentList.value.filter((item) => item.ossId !== file.ossId);
      } catch (error) {
        ElMessage.error('删除失败');
      }
    })
    .catch(() => {
      // 取消删除操作
    });
};

// 处理文件下载
const handleDownload = (file) => {
  if (file.url) {
    // 发起请求获取文件
    fetch(file.url)
      .then((response) => response.blob())
      .then((blob) => {
        // 创建一个 URL 对象
        const url = window.URL.createObjectURL(blob);
        // 创建一个 a 标签
        const a = document.createElement('a');
        // 设置 a 标签的 href 属性为文件的 URL
        a.href = url;
        // 设置下载的文件名
        a.download = file.fileName || '文件';
        // 模拟点击 a 标签进行下载
        a.click();
        // 释放 URL 对象
        window.URL.revokeObjectURL(url);
      })
      .catch((error) => {
        console.error('下载文件时出错:', error);
        ElMessage.error('下载链接无效');
      });
  } else {
    ElMessage.error('下载链接无效');
  }
};

// 处理新增
const handleAdd = () => {
  dialogTitle.value = '新增工作总结';
  form.value = {
    id: '',
    workType: '',
    summaryTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    responsible: '',
    workContent: '',
    mainAchievements: '',
    existingProblems: '',
    improvements: '',
    remarks: '',
    ossList: []
  };
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = async (row) => {
  try {
    const res = await getWorkSummaryInfo(row.id);
    if (res.code === 200) {
      dialogTitle.value = '编辑工作总结';
      form.value = { ...res.data };
      dialogVisible.value = true;
    }
  } catch (error) {
    console.error('获取工作总结详情失败:', error);
    ElMessage.error('获取详情失败');
  }
};

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该工作总结吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteWorkSummary(row.id);
      if (res.code === 200) {
        ElMessage.success('删除成功');
        await fetchTableData();
      }
    } catch (error) {
      console.error('删除工作总结失败:', error);
      ElMessage.error('删除失败');
    }
  });
};

// 表格选择改变
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

// 处理表单提交
const handleSubmit = () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = { ...form.value };
        const res = submitData.id ? await updateEWorkSummary(submitData) : await addWorkSummary(submitData);

        if (res.code === 200) {
          ElMessage.success(submitData.id ? '修改成功' : '新增成功');
          dialogVisible.value = false;
          await fetchTableData();
        }
      } catch (error) {
        console.error('提交工作总结失败:', error);
        ElMessage.error('提交失败');
      }
    }
  });
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchTableData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchTableData();
};

onMounted(() => {
  fetchTableData();
});
</script>

<style scoped lang="scss">
.bridge-work-container {
  padding: 20px;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);

  .operation-bar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    background: var(--el-bg-color-overlay);
    padding: 16px;
    border-radius: 4px;

    .left {
      .page-title {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
    }

    .right {
      display: flex;
      gap: 12px;
    }

    .custom-button {
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
      }
    }
  }

  .custom-table {
    margin-bottom: 20px;
    border-radius: 8px;
    overflow: hidden;
    background: var(--el-bg-color-overlay);

    :deep(th) {
      background: var(--el-bg-color-page) !important;
    }

    :deep(.el-table__row) {
      background-color: var(--el-bg-color-overlay);
    }

    .operation-button {
      padding: 2px 8px;
      margin: 0 2px;
      font-size: 12px;

      &.danger {
        color: var(--el-color-danger);
      }

      &:hover {
        opacity: 0.8;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.custom-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    background: var(--el-bg-color-overlay);

    .el-dialog__header {
      background: var(--el-bg-color-page);
      margin: 0;
      padding: 20px;
      border-bottom: 1px solid var(--el-border-color-light);
    }

    .el-dialog__body {
      padding: 30px 20px;
    }

    .el-dialog__footer {
      border-top: 1px solid var(--el-border-color-light);
      padding: 15px 20px;
    }
  }

  .dialog-form {
    :deep(.el-form-item__label) {
      color: var(--el-text-color-regular);
    }

    :deep(.el-input__inner) {
      background-color: var(--el-bg-color-overlay);
      border-color: var(--el-border-color);
      color: var(--el-text-color-primary);
    }
  }
}

.file-dialog {
  .file-list {
    .file-item {
      padding: 8px 0;
      border-bottom: 1px solid var(--el-border-color-lighter);

      &:last-child {
        border-bottom: none;
      }

      .el-link {
        display: flex;
        align-items: center;
        gap: 8px;
      }
    }
  }
}

.attachment-dialog {
  :deep(.el-dialog__body) {
    padding: 20px;
  }

  .attachment-container {
    max-height: 400px;
    overflow-y: auto;
  }
}

.upload-container {
  padding: 20px;

  .el-upload {
    width: 100%;

    .el-upload-dragger {
      width: 100%;
    }
  }

  .upload-progress {
    margin-top: 20px;
    padding: 16px;
    background: var(--el-fill-color-light);
    border-radius: 4px;

    .progress-text {
      color: var(--el-text-color-regular);
      font-size: 14px;

      .progress-status {
        margin-top: 8px;

        .success-text {
          color: var(--el-color-success);
        }

        .error-text {
          color: var(--el-color-danger);
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.el-upload__tip {
  margin-top: 8px;
  color: var(--el-text-color-secondary);
  font-size: 12px;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 10px;
  font-weight: 500;
}

.w-full {
  width: 100%;
}
</style>
